
package com.wd.amodel.view;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wd.amodel.R;
import com.wd.amodel.bean.Barrage;
import com.wd.amodel.bean.NoticeBean;
import com.wd.amodel.util.ThreadUtils;
import com.wd.base.util.HandlerUtils;
import com.wd.base.util.Logger;
import com.wd.base.util.StringUtils;
import com.wd.base.util.ViewUtils;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 公告消息<BR>
 *
 * @author w4425
 * @version [V5.9.3, 2021/6/9]
 * @since V5.9.3
 */
public class NoticeInfoView extends HorizontalScrollView {
    private static String TAG = "NoticeInfoView";
    /**
     * 公告的高
     */
    private static int LAYOUT_HEIGHT = 32;
    /**
     * 半屏从屏幕右侧到左侧滑出，屏幕展示速度为146px/s，匀速飘过
     */
    private static int SLIDE_SPEED = 146;

    /**
     * 公告信息标识
     */
    private static final String TYPE_NOTICE = "5";

    /**
     * 弹幕移动时长
     */
    private int duration = 18;
    /**
     * 控件宽
     */
    private int width = 1080;
    /**
     * 公告队列
     */
    private Queue<NoticeBean> mFirstQueue = new LinkedList<NoticeBean>();

    /**
     * 是否加载公告
     */
    private boolean isStart = true;
    private ObjectAnimator mAnimator;
    private boolean mUserVisibleHint = true;
    private int mConfigurationStatus = Configuration.ORIENTATION_PORTRAIT;
    private FrameLayout layoutNotice;
    private View layout;

    public NoticeInfoView(Context context) {
        super(context);
    }

    public NoticeInfoView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setUserVisibleHint(boolean mUserVisibleHint) {
        this.mUserVisibleHint = mUserVisibleHint;
    }

    public void setConfigurationStatus(int mConfigurationStatus) {
        this.mConfigurationStatus = mConfigurationStatus;
    }

    /**
     * 初始化view
     *
     * @param layout
     */
    private void initView(View layout, NoticeBean noticeBean) {
        if (noticeBean == null) {
            return;
        }
        TextView tvTitle = ViewUtils.findViewById(layout, R.id.tv_title);
        ConstraintLayout.LayoutParams tvParams = (ConstraintLayout.LayoutParams) tvTitle.getLayoutParams();
        tvParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
        tvTitle.setLayoutParams(tvParams);
        TextView tvMore = ViewUtils.findViewById(layout, R.id.tv_more);
        if (tvTitle != null) {
            tvTitle.setText(noticeBean.getMsgTitle());
        }
        if (tvMore != null) {
            tvMore.setVisibility(TextUtils.isEmpty(noticeBean.getMsg()) ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * 加载动画
     *
     * @param layout
     */
    int layoutW = width;
    private void initAnimator(View layout) {
        layout.post(new Runnable() {
            @Override
            public void run() {
                  layoutW = layout.getMeasuredWidth();
                Logger.e(TAG, "initAnimato postW= "+layoutW);
                long start = SystemClock.elapsedRealtime();
                mAnimator = ObjectAnimator.ofFloat(layout, "translationX", width, -layoutW);
                mAnimator.addListener(new Animator.AnimatorListener() {

                    @Override
                    public void onAnimationStart(Animator animator) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        Logger.e(TAG, "initAnimator end =" + (SystemClock.elapsedRealtime() - start) / 1000);
                        isStart = true;
                        if (mAnimator != null) {
                            mAnimator.cancel();
                            mAnimator = null;
                        }
                        if (layout != null) {
                            layout.clearAnimation();
                        }
                        startThread();
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {
                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }
                });
                mAnimator.setDuration(12000);
                mAnimator.start();
            }
        });

    }

    @Override
    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
        super.setVerticalScrollBarEnabled(false);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        width = getWidth();
        SimpleDateFormat df =new  SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        String date= df.format(new Date());

        Logger.e(TAG, "date222 = "+date);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        SimpleDateFormat df =new  SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        String date= df.format(new Date());

        Logger.e(TAG, "date222 = "+date);
    }

    /**
     * init公告
     *
     * @param userVisibleHint
     * @param configurationStatus
     * @param msg
     */
    public void init(boolean userVisibleHint, int configurationStatus, String msg, FrameLayout layoutNotice) {
        Logger.d(TAG, "init");
        this.layoutNotice = layoutNotice;
        setUserVisibleHint(userVisibleHint);
        setConfigurationStatus(configurationStatus);
        if (StringUtils.isEmpty(msg)) {
            Logger.w(TAG, "handleNoticeEvent msg == null");
            return;
        }
        NoticeBean noticeBean = null;
        try {
            noticeBean = new Gson().fromJson(msg, new TypeToken<NoticeBean>() {
            }.getType());
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        if (noticeBean != null && TextUtils.equals(noticeBean.getType(), TYPE_NOTICE)) {
            mFirstQueue.offer(noticeBean);
            startThread();
        }
    }

    /**
     * 执行动画
     */
    public void startThread() {
        if (isStart) {
            Logger.d(TAG, "startThread");
            HandlerUtils.post(new Runnable() {
                @Override
                public void run() {
                    handleMessage();
                }
            });
        }
    }

    private void handleMessage() {
        Logger.i(TAG, "handleMessage");
        if (mFirstQueue == null || mFirstQueue.size() <= 0) {
            return;
        }
        NoticeBean noticeBean = mFirstQueue.poll();
        if (mUserVisibleHint && Configuration.ORIENTATION_PORTRAIT == mConfigurationStatus) {
            if (layout == null) {
                layout = LayoutInflater.from(getContext()).inflate(R.layout.chatroom_item_notice_info, null);
            }
            LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, UIUtil.dp2px(layout.getContext(), LAYOUT_HEIGHT));
            layout.setLayoutParams(params);
            layout.setX(width + layout.getWidth());
            initView(layout, noticeBean);
            addLayout();
            this.setVerticalScrollBarEnabled(false);
            this.setHorizontalScrollBarEnabled(false);

            initAnimator(layout);
            SimpleDateFormat df =new  SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            String date= df.format(new Date());

            Logger.e(TAG, "date111 = "+date);
            isStart = false;
        } else {
            consumeQueue();
            isStart = false;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return true;
    }

    /**
     * 当横屏或者隐藏时，需要按照动画执行时间消耗队列
     */
    private void consumeQueue() {
        HandlerUtils.postDelay(new Runnable() {
            @Override
            public void run() {
                isStart = true;
                startThread();
            }
        }, duration * 1000);
    }

    private void addLayout() {
        if (layoutNotice != null) {
            ViewGroup parent = (ViewGroup) layout.getParent();
            if (parent != null) {
                parent.removeAllViews();
            }
            this.addView(layout);
            this.setVerticalScrollBarEnabled(false);
            layoutNotice.removeAllViews();
            layoutNotice.setVisibility(View.VISIBLE);
            layoutNotice.addView(this);
        }
    }

    /**
     * 清除数据
     */
    public void clearData() {
        if (mFirstQueue != null) {
            mFirstQueue.clear();
        }
        if (mAnimator != null) {
            mAnimator.cancel();
        }
        isStart = true;
    }

}
